package com.robusta.cityuate.services;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.utils.ConnectionUtils;

import android.content.Context;
import android.content.Intent;

public class FavoriteSpotService extends HTTPService {

	private static final String REQUEST_URL = "/spots/";
	public static final String TO_FAVORITE = "favorite";
	private static final String FAVOURITE = "/favorite";
	private static final String UNFAVOURITE = "/unfavorite";
	private Context mContext = this;



	@Override
	protected void onResponse() {
		Intent favSpotUIupdate = new Intent(assignedFilter);
		switch (responseStatusCode) {
		case HttpStatus.SC_NO_CONTENT: {
			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, true, assignedFilter,
					""+ extras.getLong(Spot.SPOT_ID));
			// update UI if active
			favSpotUIupdate.putExtra(RESUlT, true);
			sendOrderedBroadcast(favSpotUIupdate, null);
			return;
		}
		case HttpStatus.SC_UNAUTHORIZED: {
			JSONObject res;
			try {
				res = new JSONObject(responseString);
				onNoResponse(res.getString("message"));
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		}

	}

	@Override
	protected void onNoResponse(String msg) {
		// remove connection from shared pref keeping result and reason
		ConnectionUtils.setDisconnecting(mContext, false, assignedFilter, msg);
		// update UI if active
		Intent deleteSpotUIupdate = new Intent(assignedFilter);
		deleteSpotUIupdate.putExtra(RESUlT, false);
		sendOrderedBroadcast(deleteSpotUIupdate, null);

	}

	@Override
	protected HttpRequestBase initRequest() {

		if (extras.getBoolean(TO_FAVORITE)) {
			HttpPost req = new HttpPost(API_URL + REQUEST_URL
					+ extras.getLong(Spot.SPOT_ID) + FAVOURITE);
			try {
				req.setEntity(new ByteArrayEntity(("").getBytes("UTF-8")));
			} catch (UnsupportedEncodingException e) {
			}
			return req;

		} else {
			HttpDelete req = new HttpDelete(API_URL + REQUEST_URL
					+ extras.getLong(Spot.SPOT_ID) + UNFAVOURITE);
			return req;
		}
	}

}
